package com.servlet;

import com.pojo.*;
import com.service.*;
import com.util.CookieUtil;
import com.util.EmailUtil;
import com.util.ResponseUtil;
import com.util.TokenUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@WebServlet(value = "/userServlet")
public class UserServlet extends BaseServlet{
    /***
     * 登录验证
     */
    protected void login_check(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(LoginService.login_check(username,password)){
            String token= TokenUtil.getToken(new VerifyUser(username,password));
            Cookie cookie=new Cookie("Token",token);
            resp.addCookie(cookie);
            User user=new User();
            user.setUsername(username);
            //记录登录状态
            req.getSession().setAttribute(username,"true");
            resp.getWriter().write(ResponseUtil.SUCCESS("登录成功",user));
        }else{
            resp.getWriter().write(ResponseUtil.FAIL("用户名或密码错误",null));
        }
    }

    /**
     * 获取头像
     */
    protected void get_avatar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
          resp.getWriter().write(ResponseUtil.SUCCESS("获取头像",req.getSession().getAttribute("avatar")));
    }

    /**
     * 发送邮箱验证码
     */
    protected void send_code(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mailbox=req.getParameter("mailbox");
        //生成随机邮箱验证码
        String code= EmailUtil.creatCode(6);
        EmailUtil.sendEmail(code,mailbox);
        //取出qq号
        String str = mailbox.substring(0, mailbox.indexOf("@"));
        System.out.println("[info]验证码："+code);
        //将验证码存到session域中
        req.getSession().setAttribute(str,code);
        //设置验证码的过期时间为5分钟之后
        req.getSession().setMaxInactiveInterval(300);
        resp.getWriter().write(ResponseUtil.SUCCESS("已发送验证码",null));
    }

    /***
     * 注册信息验证
     */
    protected void register_check(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String code=req.getParameter("code");
        if(RegisterCheck.check_code(code,req)) {
            RegisterService.register(req);
            resp.getWriter().write(ResponseUtil.SUCCESS("注册成功",null));
        }else{
            resp.getWriter().write(ResponseUtil.FAIL("验证码错误",null));
        }
    }

    /***
     * 邮箱查重
     */
    protected void check_mailbox(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String mailbox=req.getParameter("mailbox");
        if(RegisterCheck.check_mailbox(mailbox))
        {
            resp.getWriter().write(ResponseUtil.SUCCESS("邮箱有效",null));
        }else{
            resp.getWriter().write(ResponseUtil.FAIL("邮箱已存在",null));
        }
    }

    /***
     * 获取用户基本信息
     */
    protected void get_user_msg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
            Cookie cookie= CookieUtil.findCookie("Token",req.getCookies());
            if(cookie!=null) {
                String token = cookie.getValue();
                if (TokenUtil.verify(token)) {
                    VerifyUser verifyUser = TokenUtil.get(token);
                    User user = PersonalCenterService.get_user_info(verifyUser.getUserName());
                    resp.setStatus(200);
                    resp.getWriter().write(ResponseUtil.SUCCESS("JWT验证成功",user));
                } else {
                    VerifyUser verifyUser1=TokenUtil.get(token);
                    req.getSession().setAttribute(verifyUser1.getUserName(),"false");
                    System.out.println("[info]JWT验证失败");
                    resp.getWriter().write(ResponseUtil.FAIL("JWT验证失败",null));
                }
            }else{
                System.out.println("[info]JWT验证失败");
                resp.getWriter().write(ResponseUtil.FAIL("JWT验证失败",null));
            }
    }

    /**
     * 获取用户成就
     */
    protected void get_user_success(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
            String email=req.getParameter("email");
            User user=PersonalCenterService.get_user_success(email);
            resp.getWriter().write(ResponseUtil.SUCCESS("成功获取用户成就",user));
    }

    /**
     * 判断用户登录状态
     */
    protected void judge_user_status(HttpServletRequest req, HttpServletResponse resp) throws IOException {
               String userid=req.getParameter("userid");
               String status= (String) req.getSession().getAttribute(userid);
               if(Objects.equals(status, "true")){
                   System.out.println("[info]从本地取出用户基本信息");
                   resp.getWriter().write(ResponseUtil.SUCCESS("成功获取用户信息",null));
               }else{
                    resp.getWriter().write(ResponseUtil.FAIL("请登录之后再操作",null));
               }
    }

    /***
     * 修改个人信息
     */
    protected void change_user_info(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
           User user=new User();
           user.setNickname(req.getParameter("nickname"));
           user.setUsername(req.getParameter("userid"));
           user.setGender(req.getParameter("gender"));
           user.setRegion(req.getParameter("region"));
           user.setBorndate(req.getParameter("borndate"));
           user.setIntro(req.getParameter("intro"));
           PersonalCenterService.change_user_info(user);
           resp.getWriter().write(ResponseUtil.SUCCESS("修改成功",null));
    }

    /**
     * 修改密码
     */
    protected void change_pwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
         String old_pwd=req.getParameter("old_pwd");
         String new_pwd=req.getParameter("new_pwd");
         String mail=req.getParameter("mailbox");
         String verify_code=req.getParameter("verify_code");
         String userid=req.getParameter("userid");
         if(!RegisterCheck.check_code(verify_code, req))
         {
             resp.getWriter().write(ResponseUtil.FAIL("验证码错误",null));
         }else {
             if (!PersonalCenterService.verify_pwd(old_pwd,userid)) {
                 resp.getWriter().write(ResponseUtil.FAIL("原始密码错误",null));
             }else{
                 PersonalCenterService.change_user_pwd(userid,new_pwd);
                resp.getWriter().write(ResponseUtil.SUCCESS("修改密码成功",null));
             }
         }
    }

    /**
     * 重置密码
     */
    protected void reset_pwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
         String new_pwd=req.getParameter("new_pwd");
         String mail=req.getParameter("mailbox");
         String code=req.getParameter("code");
         if(!RegisterCheck.check_code(code,req)){
             resp.getWriter().write(ResponseUtil.FAIL("验证码错误",null));
         }else{
             PersonalCenterService.change_user_pwd(mail,new_pwd);
             resp.getWriter().write(ResponseUtil.SUCCESS("重置密码成功",null));
         }
    }

    /***
     * 用户退出
     */
    protected void user_exit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
             System.out.println("[info]用户退出");
             //删除Token
             Cookie cookie=CookieUtil.findCookie("Token",req.getCookies());
             cookie.setMaxAge(0);
             resp.addCookie(cookie);
             /*标记退出状态*/
             String userid=req.getParameter("userid");
             req.getSession().setAttribute(userid,"false");
             resp.getWriter().write(ResponseUtil.SUCCESS("退出成功",null));
    }

    /**
     * 账号注销
     */
    protected void user_logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
                String userid=req.getParameter("email");
                PersonalCenterService.account_logout(userid);
                //删除Token
                Cookie cookie=CookieUtil.findCookie("Token",req.getCookies());
                if(cookie!=null) {
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }
                resp.getWriter().write(ResponseUtil.SUCCESS("账号已注销",null));
    }

    /**
     * 获取关注列表
     */
    protected void get_concern_list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
         String email=req.getParameter("email");
         List<FollowItem> followlist=new ArrayList<FollowItem>();
         followlist=PersonalCenterService.get_following_list(email);
         resp.getWriter().write(ResponseUtil.SUCCESS("成功获取关注列表",followlist));

    }

    /**
     * 取消关注
     */
    protected void cancel_concern(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
              PersonalCenterService.cancel_concern(req);
              resp.getWriter().write(ResponseUtil.SUCCESS("已取消关注",null));
    }

    /**
     *关注
     */
    protected void concern(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
              PersonalCenterService.concern(req);
              resp.getWriter().write(ResponseUtil.SUCCESS("已关注",null));
    }

    /**
     * 获取粉丝列表
     */
    protected void get_fans_list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        List<FansItem>fansItems=new ArrayList<FansItem>();
        fansItems=PersonalCenterService.get_fans_list(req.getParameter("email"));
        resp.getWriter().write(ResponseUtil.SUCCESS("成功获取粉丝列表",fansItems));
    }

    /**
     * 访问他人主页
     */
    protected void invite_others(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("[info]访问他人主页");
        String invite_id=req.getParameter("invite_id");
        resp.getWriter().write(ResponseUtil.SUCCESS("跳转到他人主页",invite_id));
    }

    /**
     * 获取要访问的人的基本信息
     */
    protected void get_invite_info(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
            String invite_id= req.getParameter("invite_id");
             User user = PersonalCenterService.get_user_info(invite_id);
            resp.getWriter().write(ResponseUtil.SUCCESS("获取到了基本信息",user));
    }

    /**
     * 获取作者基本信息
     */
    protected void get_author_info(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
       Author author = PersonalCenterService.get_author_info(req);
        resp.getWriter().write(ResponseUtil.SUCCESS("获取作者信息",author));
    }


    /**
     *获取别人关注列表
     */
    protected void get_invite_following_list(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
           String userid= req.getParameter("invite_id");
           List<FollowItem> followlist;
           followlist=PersonalCenterService.get_following_list(userid);
           resp.getWriter().write(ResponseUtil.SUCCESS("成功获取TA的关注列表",followlist));
    }

    /**
     * 获取别人粉丝列表
     */
    protected void get_invite_fans_list(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
        String userid= req.getParameter("invite_id");
        List<FansItem>fansItems;
        fansItems=PersonalCenterService.get_fans_list(userid);
        resp.getWriter().write(ResponseUtil.SUCCESS("成功获取TA的粉丝列表",fansItems));
    }

    /**
     * 根据关键词搜索用户
     */
    protected void search_user(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
            String search_content=req.getParameter("search_content");
            List<SearchUser>searchUsers=new ArrayList<>();
            String userid=req.getParameter("email");
            int page_number=Integer.parseInt(req.getParameter("page_number"));
            if(userid==null)userid="";
            searchUsers= SearchService.search_user(search_content,userid,page_number);
            resp.getWriter().write(ResponseUtil.SUCCESS("success",searchUsers));
    }

    /**
     * 管理员登录
     */
     protected void manager_login(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
               if(LoginService.manager_login(req)){
                    resp.getWriter().write(ResponseUtil.SUCCESS("登录成功",null));
               }else{
                    resp.getWriter().write(ResponseUtil.FAIL("账号或密码错误",null));
               }
     }

    /**
     * 获取所有用户
     */
    protected void get_all_user(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
              String currentPageStr=req.getParameter("currentPage");
              int currentPage=0;

              if(currentPageStr.length()>0){
                    currentPage=Integer.parseInt(currentPageStr);
              }else{
                  currentPage=1;
              }

              PageBean<User> pb=ManagerService.get_all_user(currentPage);

              resp.getWriter().write(ResponseUtil.SUCCESS("获取所有用户",pb));
    }

}

